package com.btex.app.treaty;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.entity.CoinsInfo;
import com.btex.app.pager.BaseFragment;
import com.btex.app.tools.Tools;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/26
 * @time 下午11:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */


//合约资产

public class CoinsFragment extends BaseFragment {


    @BindView(R.id.fragment_contract_assets_recy)
    RecyclerView mFragmentContractAssetsRecy;
    Unbinder unbinder;
    @BindView(R.id.fragment_contract_assets_btc)
    TextView mFragmentContractAssetsBtc;
    @BindView(R.id.fragment_contract_assets_zhehe)
    TextView mFragmentContractAssetsZhehe;
    @BindView(R.id.treaty_behavior_tv_change)
    TextView mTreatyBehaviorTvChange;
    @BindView(R.id.fragment_bibi_swiperefreshLayout)
    SwipeRefreshLayout mFragmentBibiSwiperefreshLayout;
    @BindView(R.id.fragment_contract_assets_cardview)
    CardView mFragmentContractAssetsCardview;
    @BindView(R.id.fragment_yinchang_lin)
    LinearLayout mFragmentYinchangLin;
    private CoinsAdapter mCoinsAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_contract_assets, null);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


//        Color.parseColor("#85893e3")
        if (mFragmentContractAssetsCardview != null) {
            mFragmentContractAssetsCardview.setCardBackgroundColor(getResources().getColor(R.color.bg_coins));
        }

        initRecy();
        getInfo();
        if (mFragmentYinchangLin != null) {
            mFragmentYinchangLin.setVisibility(View.INVISIBLE);
        }

        initListener();

    }

    private void initListener() {


        if (mFragmentBibiSwiperefreshLayout != null) {
            mFragmentBibiSwiperefreshLayout.setRefreshing(true);
            mFragmentBibiSwiperefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getInfo();
                }
            });
        }

        if (mTreatyBehaviorTvChange != null) {
            mTreatyBehaviorTvChange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), MoneyTransfersActivity.class).putExtra("mSettle_anchor", "BTC"));
                }
            });
        }


        if (mCoinsAdapter != null) {
            mCoinsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    CoinsInfo.DataBean.BalancesBean balancesBean = (CoinsInfo.DataBean.BalancesBean) adapter.getData().get(position);
                    startActivity(new Intent(getActivity(), MoneyTransfersActivity.class).putExtra("mSettle_anchor", balancesBean.getCoin()));
                }
            });
        }


    }

    private void initRecy() {
        if (mFragmentContractAssetsRecy != null) {
            mFragmentContractAssetsRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
            mCoinsAdapter = new CoinsAdapter();
        }


    }

    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void getInfo() {
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MY_BALANCE_MARGIN + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();

                Log.i("jhwejwhejwi93ej", result);

                if (mFragmentBibiSwiperefreshLayout != null) {
                    mFragmentBibiSwiperefreshLayout.setRefreshing(false);
                }

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {

                        Gson gson = new Gson();
                        CoinsInfo coinsInfo = gson.fromJson(result, CoinsInfo.class);

                        String total_fund_btc = coinsInfo.getData().getTotal_fund_BTC();
                        if (!TextUtils.isEmpty(total_fund_btc)) {

                            if (Double.valueOf(total_fund_btc) == 0) {
                                mFragmentContractAssetsBtc.setText("0.00000000");
                            } else {
                                if (!TextUtils.isEmpty(total_fund_btc)) {
                                    String trim = Tools.round(Double.valueOf(total_fund_btc), 8).toString().trim();
                                    mFragmentContractAssetsBtc.setText(trim);
                                }

                            }
                        }

                        String total_fund_cny = coinsInfo.getData().getTotal_fund_CNY();

                        if (!TextUtils.isEmpty(total_fund_cny)) {


                            Double aDouble = Double.valueOf(total_fund_cny);
                            if (aDouble == 0) {
                                mFragmentContractAssetsZhehe.setText("≈" + "\t" + "0.00000" + "\t" + "\t" + "CNY");
                            } else {

                                if (!TextUtils.isEmpty(total_fund_cny)) {
                                    String trim = Tools.round(aDouble, 4).toString().trim();
                                    mFragmentContractAssetsZhehe.setText("≈" + "\t" + trim + "\t" + "\t" + "CNY");
                                }

                            }

                        }

                        List<CoinsInfo.DataBean.BalancesBean> balances = coinsInfo.getData().getBalances();
                        if (mFragmentContractAssetsRecy != null && mCoinsAdapter != null) {
                            mCoinsAdapter.setNewData(balances);
                            mFragmentContractAssetsRecy.setAdapter(mCoinsAdapter);
                        }


                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//
//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_BALANCE_MARGIN + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                Log.i("jhwejwhejwi93ej", responseInfo.result);
//
//                if (mFragmentBibiSwiperefreshLayout != null) {
//                    mFragmentBibiSwiperefreshLayout.setRefreshing(false);
//                }
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//                        Gson gson = new Gson();
//                        CoinsInfo coinsInfo = gson.fromJson(responseInfo.result, CoinsInfo.class);
//
//                        String total_fund_btc = coinsInfo.getData().getTotal_fund_BTC();
//                        if (!TextUtils.isEmpty(total_fund_btc)) {
//
//                            if (Double.valueOf(total_fund_btc) == 0) {
//                                mFragmentContractAssetsBtc.setText("0.00000000");
//                            } else {
//                                if (!TextUtils.isEmpty(total_fund_btc)) {
//                                    String trim = Tools.round(Double.valueOf(total_fund_btc), 8).toString().trim();
//                                    mFragmentContractAssetsBtc.setText(trim);
//                                }
//
//                            }
//                        }
//
//                        String total_fund_cny = coinsInfo.getData().getTotal_fund_CNY();
//
//                        if (!TextUtils.isEmpty(total_fund_cny)) {
//
//
//                            Double aDouble = Double.valueOf(total_fund_cny);
//                            if (aDouble == 0) {
//                                mFragmentContractAssetsZhehe.setText("≈" + "\t" + "0.00000" + "\t" + "\t" + "CNY");
//                            } else {
//
//                                if (!TextUtils.isEmpty(total_fund_cny)) {
//                                    String trim = Tools.round(aDouble, 4).toString().trim();
//                                    mFragmentContractAssetsZhehe.setText("≈" + "\t" + trim + "\t" + "\t" + "CNY");
//                                }
//
//                            }
//
//                        }
//
//                        List<CoinsInfo.DataBean.BalancesBean> balances = coinsInfo.getData().getBalances();
//                        if (mFragmentContractAssetsRecy != null && mCoinsAdapter != null) {
//                            mCoinsAdapter.setNewData(balances);
//                            mFragmentContractAssetsRecy.setAdapter(mCoinsAdapter);
//                        }
//
//
//                    } else {
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        Log.i("weifweufhiweufhw", "1");
        if (isVisibleToUser) {
//            initRecy();
//            getInfo();
//            initListener();
            getInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void CoinsFragment(String messageEvent) {

        if (messageEvent.equals("loginsuccess")) {
            Log.i("wehfowiefwhefo", "111111111111111");
            getInfo();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
